package com.tjmc.nsia.core.controller.front;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.tjmc.nsia.core.dao.entity.NsiaExam;
import com.tjmc.nsia.core.dao.entity.NsiaUser;
import com.tjmc.nsia.core.domain.AjaxResult;
import com.tjmc.nsia.core.dto.resp.NsiaExamCategoryExtend;
import com.tjmc.nsia.core.dto.resp.NsiaExamQuestion;
import com.tjmc.nsia.core.dto.resp.NsiaExamQuestionAnswer;
import com.tjmc.nsia.core.service.NsiaExamService;
import com.tjmc.nsia.core.service.NsiaUserService;
import com.tjmc.nsia.core.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  控制器
 * </p>
 *
 * @author ${author}
 * @date 2024/07/10
 */
@RestController
@RequestMapping("/exam")
public class NsiaExamController {

    @Autowired
    private NsiaExamService nsiaExamService;

    @Autowired
    private NsiaUserService nsiaUserService;

    @Autowired
    private ResourceService resourceService;

    @GetMapping("/categories")
    public AjaxResult listCategories() {
        List<NsiaExamCategoryExtend> categoryExtends = nsiaExamService.getAllCategories();
        if(!CollectionUtil.isEmpty(categoryExtends)) {
            return AjaxResult.success(categoryExtends);
        }
        return AjaxResult.error("查询为空");
    }

    @SaIgnore
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart("exam") NsiaExam exam, @RequestParam("file") MultipartFile file) {
        if(null != file) {
            String path = resourceService.uploadFile(file);
            exam.setFilePath(path);
            List<NsiaExamQuestion> questions = nsiaExamService.parseExamFile(path);
            exam.setQuestionAnswer(JSONObject.from(new NsiaExamQuestionAnswer(path, exam.getTitle(), questions)));
            exam.setUpdateTime(LocalDateTime.now());
            return AjaxResult.success(nsiaExamService.save(exam));
        }
        return AjaxResult.error();
    }

    @GetMapping("/exam")
    public AjaxResult getExamById(@RequestParam("examId") Integer examId) {
        return AjaxResult.success(nsiaExamService.getById(examId));
    }

    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody NsiaExamQuestionAnswer nsiaExamQuestionAnswer) {
        NsiaUser nsiaUser = nsiaUserService.getLoginUser();
        return AjaxResult.success(nsiaExamService.submit(nsiaUser, nsiaExamQuestionAnswer));
    }
}